# coding=utf-8
from django.shortcuts import render_to_response, redirect
from models import AccessLog, Project, Module, Function


# Create your views here.
def pv_count_wrapper(fn):
    def wrapper(request, *args, **kwargs):
        x_forward_for = request.META.get('HTTP_X_FORWARDED_FOR')

        if x_forward_for:
            ip = x_forward_for.split(',')[0]
        else:
            ip = request.META.get('REMOTE_ADDR')

        log = AccessLog(route=request.path, ip=ip)
        log.save()

        return fn(request, *args, **kwargs)

    return wrapper


@pv_count_wrapper
def index1(request):
    projects = Project.objects.all().order_by('-id')

    if len(projects) == 0:
        pass

    project_id = None
    try:
        project_id = int(request.GET.get("id"))
    except:
        pass

    if project_id:
        display_project = filter(lambda p: p.id == project_id, projects)[0]
    else:
        display_project = projects[0]
        project_id = display_project.id

    modules = Module.objects.filter(project_id_id=project_id)
    functions = Function.objects.filter(project_id_id=project_id).order_by('-module_id')
    # statistics = Statistics.objects.filter(project_id_id=project_id).order_by('-module_id')

    return render_to_response('index.html', locals())


@pv_count_wrapper
def index(request, project_id):
    projects = Project.objects.all().order_by('-id')

    if len(projects) == 0:
        pass
    #
    # if !project_id
    #     project_id =
    #

    if project_id:
        display_project = Project.objects.filter(id=project_id)[0]
    else:
        display_project = projects[0]
        project_id = display_project.id

    modules = Module.objects.filter(project_id_id=project_id)
    functions = Function.objects.filter(project_id_id=project_id).order_by('-module_id')
    # statistics = Statistics.objects.filter(project_id_id=project_id).order_by('-module_id')

    return render_to_response('index.html', locals())


@pv_count_wrapper
def index_redirect(request):
    projects = Project.objects.all().order_by('-id')
    project_id = projects[0].id

    return redirect('/' + str(project_id) + '/', permanent=True)


def index_post(request):
    module_ids = set()

    funcs_data = {}

    for key, data in request.POST.items():
        if not key.startswith(u"f-"):
            continue

        _, module_id, func_id = key.split("-")
        funcs_data[func_id] = data
        module_ids.add(module_id)

    func_objs= Function.objects.filter(id__in=funcs_data.keys()).all()
    module_objs = Module.objects.filter(id__in=list(module_ids))

    module_to_func = {}

    for func_obj in func_objs:
        data = funcs_data.get(str(func_obj.id))
        func_obj.completion = data == "on"
        func_obj.save()

        module_id = func_obj.module_id.id
        if module_id in module_to_func:
            module_to_func[module_id].append(func_obj)
        else:
            module_to_func[module_id] = [func_obj]

    module_to_stat = {}
    for module_id, f_list in module_to_func.items():
        f_on_list = filter(lambda f: f.completion, f_list)
        module_to_stat[module_id] = len(f_on_list) / float(len(f_list)) * 100

    for module in module_objs:
        module.completion_rate = module_to_stat[module.id]
        module.save()

    return redirect('/' + str(module_objs[0].project_id.id) + '/')
